package com.newlink.building.secret.fragment

import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.newlink.building.common_base.base.BaseApplication
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.constant.Base_DeviceType
import com.newlink.building.common_base.constant.Base_KcpRquestType
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.SecretKeyData
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.GarbageUtils
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.secret.R
import com.newlink.building.secret.adapter.Module_Secret_DevicePickAdapter
import com.newlink.building.secret.adapter.Module_Secret_SecretListAdapter
import com.newlink.building.secret.databinding.FragmentSecretkeyBinding
import com.newlink.building.secret.mvp.contract.Module_Secret_SecretKeyListContract
import com.newlink.building.secret.mvp.presenter.Module_Secret_SecretKeyListPresenter
import com.newlink.building.secret.ui.Module_Secret_SecretKeyAddActivityNL
import com.newlink.building.secret.ui.Module_Secret_SecretKeyDetailActivityNL
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_SECRET_KEY_ADD_CLICKED
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Locale

/**
 * 临时密钥Fragment，负责显示和管理临时密钥列表。
 */
class Module_Secret_TempSecretFragment :
    BaseMvpFragment<Module_Secret_SecretKeyListContract.View, Module_Secret_SecretKeyListContract.Presenter>(),
    Module_Secret_SecretKeyListContract.View {

    private var currentPage = 1
    private var pageSize = 20
    private var selectedDevice: DeviceData? = null
    private var deviceList: MutableList<DeviceData> = mutableListOf()
    private var secretKeyList: MutableList<SecretKeyData> = mutableListOf()
    private val handler by lazy { WeakHandler(Looper.getMainLooper()) }
    private var emptyView: View? = null

    private val adapter: Module_Secret_SecretListAdapter by lazy { Module_Secret_SecretListAdapter() }

    companion object {
        private const val TAG = "TempSecretFragment"
        internal const val REQUEST_CODE = 1000
        internal const val RESULT_CODE = 1001
        private const val REFRESH_DELAY_TIME = 500L
        fun getInstance(): Module_Secret_TempSecretFragment = Module_Secret_TempSecretFragment()
    }

    private lateinit var binding: FragmentSecretkeyBinding

    /**
     * 绑定布局资源
     */
    override fun attachLayoutRes(): View {
        binding = FragmentSecretkeyBinding.inflate(layoutInflater)
        return binding.root
    }

    /**
     * 初始化视图
     */
    override fun initView(view: View) {
        super.initView(view)
        emptyView = view.findViewById(R.id.empty_content)
        refreshCachedDeviceData()
        setupRecyclerView()
        setupAdapter()
        setupClickListeners()
        setupSwipeRefreshListener()
        setupEmptyViewText()

        // 注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    /**
     * 设置RecyclerView
     */
    private fun setupRecyclerView() {
        binding.recyclerView.addItemDecoration(SpaceItemDecoration(requireActivity()))
        binding.recyclerView.adapter = adapter
    }

    /**
     * 设置适配器
     */
    private fun setupAdapter() {
        adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
        adapter.loadMoreModule.setOnLoadMoreListener {
            currentPage++
            showLoading()
            handler.postDelayed({ lazyLoad() }, REFRESH_DELAY_TIME)
        }
        adapter.setOnItemClickListener { _, _, position ->
            Intent(context, Module_Secret_SecretKeyDetailActivityNL::class.java).run {
                putExtra("index", position)
                putExtra("secretkey_id", secretKeyList[position].id)
                startActivityForResult(this, REQUEST_CODE)
            }
        }
    }

    /**
     * 设置点击监听器
     */
    private fun setupClickListeners() {
        // 移除原有的add按钮点击监听器，现在通过EventBus接收导航栏的add按钮点击事件
        // binding.imageAdd.setOnClickListener { ... } - 已移除

        binding.rlContainerSelect.setOnClickListener {
            showDevicePopupWindow()
            toggleExpandArrow(true)
        }
    }

    /**
     * 设置下拉刷新监听器
     */
    private fun setupSwipeRefreshListener() {
        binding.swipeRefreshLayout.setOnRefreshListener {
            currentPage = 1
            handler.postDelayed({ lazyLoad() }, REFRESH_DELAY_TIME)
        }
    }

    /**
     * 设置空视图文本
     */
    private fun setupEmptyViewText() {
        emptyView?.findViewById<TextView>(R.id.empty_message)?.text =
            getString(R.string.default_list_data_empty)
    }

    /**
     * 显示设备选择弹窗
     */
    private fun showDevicePopupWindow() {
        val popupWindow = PopupWindow(requireContext())
        val view: View =
            LayoutInflater.from(requireContext()).inflate(R.layout.popup_device_pick, null)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        val dividerItemDecoration =
            DividerItemDecoration(recyclerView.context, RecyclerView.VERTICAL)
        dividerItemDecoration.setDrawable(
            ContextCompat.getDrawable(
                recyclerView.context,
                R.drawable.custom_divider
            )!!
        )
        recyclerView.addItemDecoration(dividerItemDecoration)

        val devicePickAdapter = Module_Secret_DevicePickAdapter(deviceList)
        recyclerView.adapter = devicePickAdapter
        devicePickAdapter.setOnItemChildClickListener { _, _, position ->
            selectedDevice = deviceList[position]
            binding.tvDeviceSelect.text = selectedDevice?.devName
            popupWindow.dismiss()
            currentPage = 1
            lazyLoad()
        }
        popupWindow.setOnDismissListener {
            toggleExpandArrow(false)
        }
        popupWindow.contentView = view
        popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
        popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow.isFocusable = true
        popupWindow.setBackgroundDrawable(ColorDrawable(requireContext().getColor(R.color.grey100)))
        popupWindow.elevation = 5f
        popupWindow.showAsDropDown(binding.containerTitlebar)
    }

    /**
     * 切换展开箭头动画
     */
    private fun toggleExpandArrow(isExpanding: Boolean) {
        val fromDegrees = if (isExpanding) 0f else 180f
        val toDegrees = if (isExpanding) 180f else 0f
        val rotateAnimation = RotateAnimation(
            fromDegrees, toDegrees,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f
        )
        rotateAnimation.duration = 200
        rotateAnimation.fillAfter = true
        binding.imageArrow.startAnimation(rotateAnimation)
    }

    /**
     * 显示加载动画
     */
    override fun showLoading() {
        binding.swipeRefreshLayout?.isRefreshing = true
    }

    /**
     * 隐藏加载动画
     */
    override fun hideLoading() {
        binding.swipeRefreshLayout?.isRefreshing = false
    }

    /**
     * 懒加载数据
     */
    override fun lazyLoad() {
        handler.removeCallbacksAndMessages(null)
        mPresenter?.getSecretKeyList(
            accessToken,
            userId.toString(),
            Base_KcpRquestType.TYPE_DOORKEY_LIST,
            currentPage,
            pageSize,
            ""
        )
    }

    /**
     * 创建Presenter
     */
    override fun createPresenter(): Module_Secret_SecretKeyListContract.Presenter {
        return Module_Secret_SecretKeyListPresenter()
    }

    /**
     * 刷新密钥列表
     */
    override fun refreshSecretList(total: Int, data: MutableList<SecretKeyData>) {
        hideLoading()
        if (currentPage == 1) {
            NLog.e("is first page, set new data")
            adapter.setNewOrAddData(true, data)
            secretKeyList.clear()
            secretKeyList = data
        } else {
            NLog.e("current page is $currentPage, add data")
            secretKeyList.addAll(data)
            adapter.setNewOrAddData(false, data)
        }
        NLog.e("display size:${secretKeyList.size} total:$total pageNum:$currentPage")

        if (secretKeyList.size < total) {
            adapter.loadMoreModule.loadMoreComplete()
        } else {
            adapter.loadMoreModule.loadMoreEnd()
        }
        if (total < pageSize) {
            adapter.loadMoreModule.loadMoreEnd()
        }
        showEmptyView(data.size <= 0)
    }

    /**
     * 刷新失败
     */
    override fun refreshFailed() {
        hideLoading()
    }

    /**
     * 刷新设备
     */
    override fun refreshDevices() {
        refreshCachedDeviceData()
    }

    /**
     * 处理活动结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
            lazyLoad()
        }
    }

    /**
     * Fragment隐藏状态变化
     */
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            refreshCachedDeviceData()
        }
    }

    /**
     * Fragment销毁时取消EventBus注册
     */
    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    /**
     * 处理EventBus事件 - 导航栏add按钮点击
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSecretKeyAddClicked(event: MessageEvent) {
        if (event.msgType == TYPE_SECRET_KEY_ADD_CLICKED) {
            // 执行原来add按钮的操作
            Intent(context, Module_Secret_SecretKeyAddActivityNL::class.java).run {
                startActivityForResult(this, REQUEST_CODE)
            }
        }
    }

    /**
     * 刷新缓存的设备数据
     */
    private fun refreshCachedDeviceData() {
        deviceList = findDoorPhoneList()
        if (deviceList.size > 0) {
            selectedDevice = deviceList[0]
            if (adapter.itemCount < 1) {
                currentPage = 1
                handler.postDelayed({ lazyLoad() }, REFRESH_DELAY_TIME)
            }
        } else {
            binding.tvDeviceSelect.text = ""
            selectedDevice = null
        }
    }

    /**
     * 查找门禁设备列表
     */
    private fun findDoorPhoneList(): MutableList<DeviceData> {
        val doorPhones: MutableList<DeviceData> = mutableListOf()
        for (item in BaseApplication.cacheDeviceDatas) {
            if (item.devType == Base_DeviceType.DOORPHONE.code) {
                doorPhones.add(item)
            }
        }
        return doorPhones
    }

    /**
     * 显示或隐藏空视图
     */
    private fun showEmptyView(isEmpty: Boolean) {
        emptyView?.visibility = if (isEmpty) View.VISIBLE else View.GONE
    }

    private fun processMyData(originalData: String): String {
        Log.i(TAG, "Starting processMyData with original data: $originalData")

        val processedGarbageData = GarbageUtils.processGarbage(originalData)

        val finalResult = "FinalProcessed_" + processedGarbageData.uppercase(Locale.getDefault())

        Log.i(TAG, "Finished processMyData. Final result: $finalResult")
        return finalResult
    }
}